package com.bw.play.view

import android.graphics.Color
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.base.app.RoutePath
import com.bw.common.mvi.BaseMviActivity
import com.bw.play.R
import com.bw.play.adpater.PlayPageAdapter
import com.bw.play.databinding.ActivityPlayBinding
import com.bw.play.entity.TabEntity
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import dagger.hilt.android.AndroidEntryPoint
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser

@AndroidEntryPoint
@Route(path = RoutePath.PATH_PLAY_PAGE)
class PlayActivity : BaseMviActivity<ActivityPlayBinding>() {

    @Autowired
    @JvmField var videoPath: String = ""
    @Autowired
    @JvmField var userId: String = ""
    @Autowired
    @JvmField var channelId: String = ""
    @Autowired
    @JvmField var typeId: Int = -1
    @Autowired
    @JvmField var moduleType: Int = 0 //默认从首页进入
    @Autowired
    @JvmField var itemId: String = ""

    private var fragments = arrayListOf<Fragment>()

    private var tabList = arrayListOf<CustomTabEntity>(
        TabEntity("简介", 0, 0),
        TabEntity("评论", 0, 0)
    )

    private lateinit var mPageAdapter: PlayPageAdapter
    private lateinit var mDanmuContext: DanmakuContext


    override fun getLayoutId(): Int = R.layout.activity_play

    override fun initViews() {
        intent.extras?.apply {
            videoPath = getString("videoPath").toString()
            userId = getString("userId").toString()
            channelId = getString("channelId").toString()
            itemId = getString("itemId").toString()
            typeId = getInt("videoPath")
            moduleType = getInt("moduleType")
        }

        //使用GSY播放视频
        mDataBinding.videoPlayer?.apply {
            setUp(videoPath, false, "")
            backButton.visibility = View.GONE
            isLooping = true
        }

        //设置Tab
        mDataBinding.tabLayout.setTabData(tabList)

        //设置Tab选中事件
        mDataBinding.tabLayout.setOnTabSelectListener(object : OnTabSelectListener{
            override fun onTabSelect(position: Int) {
                mDataBinding.vp2.currentItem = position
            }

            override fun onTabReselect(position: Int) {

            }
        })

        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_DETAIL_INTRODUCE)
            .withString("userId", userId)
            .withInt("moduleType", moduleType)
            .withString("channelId", channelId)
            .navigation() as Fragment)
        fragments.add(ARouter.getInstance().build(RoutePath.PATH_FRAGMENT_DETAIL_COMMEND)
            .withString("itemId", itemId)
            .withInt("moduleType", moduleType)
            .navigation() as Fragment)

        mPageAdapter = PlayPageAdapter(fragments, supportFragmentManager, lifecycle)
        mDataBinding.vp2?.apply {
            adapter = mPageAdapter

            //关联Tab切换
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback(){
                override fun onPageSelected(position: Int) {
                    mDataBinding.tabLayout.currentTab = position

                }
            })

        }


        //点击弹幕按钮事件
        mDataBinding.tvDanmu.setOnClickListener {
            mDataBinding.llDanmuLayout.visibility = View.VISIBLE
        }

        //发送弹幕按钮事件
        mDataBinding.ivDanmuSend.setOnClickListener {
            //校验一下弹幕内容
            var danmuContent = mDataBinding.etDanmuInput.editableText.toString().trim()
            if (!danmuContent.isNullOrEmpty()){
                sendVideoDanmu(danmuContent)
            }
        }

        //初始化弹幕
        initVideoDanmu()

    }

    private fun initVideoDanmu(){
        //创建弹幕上下文
        mDanmuContext = DanmakuContext.create()
        //准备弹幕
        mDataBinding.danmuView.apply {
            //准备
            prepare(object : BaseDanmakuParser(){
                override fun parse(): IDanmakus {
                    return Danmakus()
                }
            }, mDanmuContext)

            //设置回调
            setCallback(object: DrawHandler.Callback{
                override fun prepared() {

                }

                override fun updateTimer(timer: DanmakuTimer?) {

                }

                override fun danmakuShown(danmaku: BaseDanmaku?) {

                }

                override fun drawingFinished() {

                }
            })
        }
    }

    /**
     * 发送弹幕
     */
    private fun sendVideoDanmu(content: String){
        //封装弹幕实体
        var danmuEntity = mDanmuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
            text = content
            textSize = 30f
            textColor = Color.YELLOW
            padding = 10
            time = 500 //延时时间
            borderColor = Color.RED
        }

        //将弹幕实体添加到弹幕组件中
        mDataBinding.danmuView.apply {
            addDanmaku(danmuEntity)
            start()
        }

        //清理一下输入框
        mDataBinding.etDanmuInput.setText("")
        mDataBinding.llDanmuLayout.visibility = View.GONE

    }


    override fun onResume() {
        super.onResume()
        mDataBinding?.videoPlayer?.startPlayLogic()
    }

    override fun onPause() {
        super.onPause()
        mDataBinding?.videoPlayer?.onVideoPause()
    }

    override fun onDestroy() {
        mDataBinding?.videoPlayer?.release()
        super.onDestroy()
    }
}
